package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.activity.BookCommentFragmentActivity;
import com.auto.learning.activity.MyMessageActivity;
import com.auto.learning.activity.MyMessageReplyActivity;
import com.auto.learning.adapter.RemindAdapter;
import com.auto.learning.bean.RemindBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.Handle;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class RemindFragment extends Fragment {
	private final static int DELETE = 1;
	private final static int DELETE_SUCCESS = 2;
	private final static int REPLY = 3;
	private PullToRefreshListView listview_remind;
	private int pageIndex = 0;
	private ArrayList<RemindBean> remindList = new ArrayList<RemindBean>();
	private View lvProductFooter,headView;
	private TextView lvProductFooterMore;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more,tv_tip;
	private LinearLayout lvLinear_more;
	private RemindAdapter adapter;
	
	private int delId = 0;

	private Handle handle = new Handle(getActivity()) {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				MyUserInfo.getInstance().getUserInfoBean().setRemindUnread(0);
				ResponeResult result = (ResponeResult) msg.obj;
				ArrayList<RemindBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<RemindBean>>() {}.getType());
				String bottom = "";
				if (pageIndex == 0) {
					remindList.clear();
					remindList.addAll(resultList);
				} else {
					remindList.addAll(resultList);
				}
//				((MyMessageActivity)getActivity()).HiddenRemindNotify();
				showTips();
				if (resultList.size() >= 10) {
					pageIndex ++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				}else {
					if(getActivity()!=null){
						bottom = getActivity().getResources().getString(R.string.text_no_data);
					}
					
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}
				if (listview_remind != null) {
					listview_remind.onRefreshComplete();
					listview_remind.setTag(0);
				}
				if (remindList != null && remindList.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				try {
					if (listview_remind != null) {
						listview_remind.onRefreshComplete();
						listview_remind.setTag(0);
					}
					CommonMethod.makeNotice(getActivity(), msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case DELETE_SUCCESS:
				if (delId > 0) {
					int size = remindList.size();
					for (int i = 0; i < size; i++) {
						if (remindList.get(i).getId() == delId) {
							remindList.remove(i);
							showTips();
							if (adapter != null) {
								adapter.notifyDataSetChanged();
							}
							break;
						}
					}
				}
				break;
			case REPLY:
				int m_posotion = msg.arg1;
				Intent intent = new Intent(getActivity(), MyMessageReplyActivity.class);
				intent.putExtra("remindId", remindList.get(m_posotion).getId());
				intent.putExtra("replyId", remindList.get(m_posotion).getReplyId());
				startActivity(intent);
				break;
			case DELETE:
				final int position = msg.arg1;
				String[] a = {"确定","取消"};
				CommonMethod.showDialog(getActivity(), a, "确定要删除这条消息吗?", new DialogListener() {
					
					@Override
					public void otherButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
					
					@Override
					public void okButtonClick(Dialog dialog) {
						dialog.dismiss();
						deleteMsg(remindList.get(position).getId());
					}
					
					@Override
					public void cancelButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
				});
				break;
			}
		}
	};
	
	private void showTips(){
		if (remindList.size() == 0) {
			if (listview_remind.getHeaderViewsCount() == 1) {
				listview_remind.addHeaderView(headView);
			}
			lvProductFooter.setVisibility(View.GONE);
			listview_remind.setDivider(new ColorDrawable(Color.GRAY));  
			listview_remind.setDividerHeight(0);
		} else {
			listview_remind.removeHeaderView(headView);
			lvProductFooter.setVisibility(View.VISIBLE);
			listview_remind.setDivider(new ColorDrawable(Color.GRAY));  
			listview_remind.setDividerHeight(1);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_remind, null);
		inintView(view);
		return view;
	}

	private void inintView(View view) {
		headView = LayoutInflater.from(getActivity()).inflate(R.layout.remind_head_view, null);
		tv_tip = (TextView) headView.findViewById(R.id.tv_tip);
		tv_tip.setText("没有新消息，是因为在等待好消息");
		listview_remind = (PullToRefreshListView) view.findViewById(R.id.listview_remind);
		adapter = new RemindAdapter(getActivity(), remindList, handle);
		listview_remind.setSelector(new ColorDrawable(Color.TRANSPARENT));
		listview_remind.setAdapter(adapter);
		listview_remind.setDivider(new ColorDrawable(Color.GRAY));  
		listview_remind.setDividerHeight(1);
		lvProductFooter = getActivity().getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);
		lvProductFooter.setBackgroundColor(getActivity().getResources().getColor(R.color.white));
		listview_remind.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pageIndex = 0;
				getData();
			}
		});
		
		listview_remind.addFooterView(lvProductFooter);
		/*lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getData();
			}
		});*/
		listview_remind.setTag("0");
		lvBtn_more.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getData();
			}
		});
		listview_remind.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listview_remind.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_no_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int lvDataState = Integer.parseInt((listview_remind.getTag().toString()));
				if (scrollEnd && lvDataState == 0) {
					listview_remind.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = listview_remind.getCount() - 2;   
					getData();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				listview_remind.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		listview_remind.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (remindList != null && remindList.size() >= position) {
					Log.d("position", position +"");
					RemindBean remindBean = remindList.get(position - 1);
					Intent mIntent = new Intent(getActivity(), BookCommentFragmentActivity.class);
					mIntent.putExtra("bookId", remindBean.getBookId());
					mIntent.putExtra("commentId", remindBean.getCommentId());
					mIntent.putExtra("bookName", remindBean.getBookName()+"");
					mIntent.putExtra("imgFace", remindBean.getImgFace()+"");
					mIntent.putExtra("imgFacePlay",remindBean.getImgFacePlay()+"");
					mIntent.putExtra("commentUserName", remindBean.getUserName()+"");
					startActivity(mIntent);
				}
			}
		});
		listview_remind.clickRefresh();
	}

	public void getData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.REMIND_LIST, params, handle, HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}
	
	public void deleteMsg(int id){
		delId = id;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("idList", String.valueOf(id)));
		HttpRequestHelper.executeHttpDataNoData(getActivity(),HttpRequestHelper.REMIND_DEL,params,handle,DELETE_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}

}
